<style lang="less" scoped>
.main-keyword-group {
    .btn-wrap {
        padding: 5px 0;
    }
    .online,
    .offline {
        margin-left: 0;
    }
    .second-row .manage-templet {
        margin-top: 5px;
    }
    .group {
        display: inline-block;
        vertical-align: top;
    }
}
</style>
<template>
    <div class="main main-keyword-group">
        <div class="main-header">
            <el-breadcrumb>
                <el-breadcrumb-item :to="{ path: '/types' }">票券类型管理</el-breadcrumb-item>
                <el-breadcrumb-item>票券类型管理</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="main-menus">
                <el-button type="primary" icon="plus" @click="editItem({}, 'top')">新增票券大类</el-button>
                <el-button type="primary" icon="plus" @click="editItem({}, '新增')">新增票券</el-button>
            </div>
        </div>
            <div class="main-filters">
            <el-form :inline="true" :model="query">
                <el-form-item label="票券大类">
                    <el-select v-model="query.parent_id">
                        <el-option label="全部" value="all" key=""></el-option>
                        <el-option
                            v-for="item in parents"
                            :label="item.name"
                            :value="item.id"
                            :key="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="票券类型">
                    <el-select v-model="query.parent_id">
                        <el-option label="全部" value="all" key=""></el-option>
                        <el-option
                            v-for="item in parents"
                            :label="item.name"
                            :value="item.id"
                            :key="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item> -->
            </el-form>
        </div>
        <div class="main-actions">
            <div class="main-actions-label">
                共<em>{{itemsData.pagination.total}}</em>条
            </div>
             <div class="main-actions-btns">
                <el-button @click="exportData">导出报表</el-button>
            </div>
        </div>
        <el-table
            border
            element-loading-text="Loading..."
            v-loading.body="!itemsData.$resolved"
            :data="itemsData.items"
            @sort-change="onSortItems"
            @selection-change="onSelect"
        >
            <el-table-column sortable="custom" prop="id" label="ID" width="80"></el-table-column>
            <el-table-column width="150" label="票券名称" inline-template>
                <div>
                    <span>{{ row.parent ? row.parent.name : '-' }}-{{row.name}}</span>
                </div>
            </el-table-column>
            <el-table-column prop="num" label="库存详情" inline-template>
                 <div>
                   <el-tag v-for="(item, index) in row.nums" :type="statusAlias[item.status].icon">{{statusAlias[item.status].name}}: {{item.count}}</el-tag>
                </div>
            </el-table-column>
            <!-- <el-table-column  width="100" label="级别" inline-template>
                <div>
                    <span v-if="row.parent_id && row.grand_id">三级级</span>
                    <span v-if="row.parent_id && row.grand_id === 0">二级</span>
                    <span v-if="row.parent_id === 0 && row.grand_id === 0">一级</span>
                </div>
            </el-table-column>
            -->
            <el-table-column width="150" label="票券大类" inline-template>
                <div>
                    <span>{{ row.parent ? row.parent.name : '-' }}</span>
                </div>
            </el-table-column>
            <!-- <el-table-column label="孙子票券类型" inline-template>
                <div>
                    <span v-for="item in row.subChildrens"> &nbsp {{ item.name }}</span>
                </div>
            </el-table-column> -->
            <!-- <el-table-column label="状态属性" width="100" inline-template>
                <div>
                    <el-tag type="success" v-if="row.status === 1">已上架</el-tag>
                    <el-tag type="warning" v-else>已下架</el-tag>
                </div>
            </el-table-column> -->
            <!-- <el-table-column sortable="custom" prop="priority" label="排序"></el-table-column> -->
            <el-table-column label="操作" inline-template width="200">
                <div class="item-menus">
                    <el-button size="small" @click="editItem(row, 1)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteItem(row)">删除</el-button>
                    <!-- <el-button size="small" type="success" v-if="row.grand_id === 0 && row.parent_id === 0" @click="editItem(row, 2)">新增票券</el-button> -->
                </div>
            </el-table-column>
        </el-table>

        <el-pagination
            v-if="itemsData.$resolved"
            layout="prev, pager, next, jumper"
            :total="itemsData.pagination.total"
            :current-page="query.page_num"
            :page-size="query.page_size"
            @current-change="onPageChange"
        >
        </el-pagination>

        <el-dialog
            :title="editData.title"
            :visible.sync="editDialogVisible"
            size="tiny"
        >
            <el-form :model="editData">
                <el-form-item label="类型名称">
                    <el-input v-model="editData.name" placeholder="输入票券类型名"></el-input>
                </el-form-item>
                <el-form-item label="票券开头编号" v-if="top === 0">
                    <el-input v-model="editData.code" placeholder="输入票券开头编号"></el-input>
                </el-form-item>
                <el-form-item label="所属大类" v-if="top === 0">
                    <el-select v-model="editData.parent_id">
                        <el-option
                            v-for="item in parents"
                            :label="item.name"
                            :value="item.id"
                            :key="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-for="attr in attrs" v-bind:key="attr.id" :label="attr.name" v-if="top === 0">
                    <el-checkbox-group v-model="attr.values" @change="onAttrChange(attr)">
                        <el-checkbox v-for="item in attr.items" v-bind:key="item.id" :label="item">{{item.name}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="节假日" v-if="top === 0">
                    <el-checkbox-group v-model="editData.dates">
                        <el-checkbox v-for="item in dates" v-bind:key="item.id" :label="item">{{item.name}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEdit">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import ListController from '../controllers/list';

import TypeModel from '../models/type';
import AttributeModel from '../models/attribute';
import Promise from 'bluebird';
import DateModel from '../models/special-date';

import TicketModel from '../models/ticket';

export default new ListController({
    data() {
        return {
            ListModel: TypeModel,

            query: {
                page_num: 1,
                page_size: 20,
                parent_id: 'all',
                grand_id: 'all',
                status: 'all',
                sort: ''
            },
            top: 0,
            statusAlias: {
                [TicketModel.PENDING]: {
                    icon: 'warning',
                    name: '待审核'
                },
                [TicketModel.UNUSED]: {
                    icon: 'success',
                    name: '未使用'
                },
                [TicketModel.OFFLINE]: {
                    icon: 'gray',
                    name: '未出票'
                },
                [TicketModel.READY]: {
                    icon: 'warning',
                    name: '备售'
                },
                [TicketModel.USED]: {
                    icon: 'success',
                    name: '已使用'
                },
                [TicketModel.COMPLETED]: {
                    icon: 'success',
                    name: '已核销'
                }
            },
            // statusMap: {
            //     PENDING: TempletModel.PENDING,
            //     ONLINE: TempletModel.ONLINE,
            //     OFFLINE: TempletModel.OFFLINE,
            //     REJECTED: TempletModel.REJECTED
            // },
            // statusAlias: {
            //     [TempletModel.PENDING]: {
            //         icon: 'warning',
            //         name: '待审核'
            //     },
            //     [TempletModel.ONLINE]: {
            //         icon: 'success',
            //         name: '已上架'
            //     },
            //     [TempletModel.OFFLINE]: {
            //         icon: 'gray',
            //         name: '已下架'
            //     },
            //     [TempletModel.REJECTED]: {
            //         icon: 'danger',
            //         name: '未通过'
            //     }
            // },

            parents: [],
            grands: [],

            editData: {
                name: '', 
                code: '', 
                parents: [],
                parent_id: 0,
                grand_id: 0,
            },
            editDialogVisible: false,
            attrs: [],
            dates: []
        };
    },
    methods: {
        beforeLoadItems() {
            return Promise.all([
                this.loadParents(),
                // this.loadGrands(),
                this.loadAttrs(),
                this.loadDates()
            ]);
        },
        loadGrands() {
            return TypeModel.query({
                parent_id: 0,
                grand_id: 0
            })
            .$promise
            .then(types => {
                this.grands = types.items;
                this.editData.parent_id = types.items[0].id;
            });
        },
        loadParents() {
            return TypeModel.query({
                parent_id: 0
            })
            .$promise
            .then(types => {
                this.parents = types.items;
            });
        },
        debugItem(row) {
            this.$confirm('确认调试该项？')
            .then(() => {
                this.ListModel.update({
                    id: row.id,
                    status: 1
                }).$promise;
            })
            .catch(err => {
                throw new Error(err);
            });
        },
        pullItem(row) {
            this.$confirm('确认下线该项？')
            .then(() => {
                const params = Object.assign({}, row, {
                    id: row.id,
                    status: 0
                });
                this.ListModel.update(params).$promise;
            })
            .then(() => {
                this.$message({
                    message: '下线成功！',
                    type: 'success'
                });

                this.loadItems();
            })
            .catch(err => {
                this.$message.error(err);
            });
        },
        pushItem(row) {
            this.$confirm('确认上线该项？')
            .then(() => {
                return this.ListModel.update({
                    id: row.id,
                    status: 1
                }).$promise
                .then(() => {
                    this.loadItems();
                });
            })
            .catch(err => {
                throw new Error(err);
            });
        },
        deleteItem(row) {
            this.$confirm('确认删除该票券类型？')
            .then(() => {
                return this.ListModel.delete({
                    id: row.id
                }).$promise;
            })
            .then(() => {
                return this.loadItems();
            })
            .catch(err => {
                throw new Error(err);
            });
        },
        editItem(row, type) {
            if(type === 'top' || row.parent_id === 0) {
                this.top = 1
            }
            else {
                this.top = 0;
            }
            if(row.id > 0) {
                this.attrs.forEach(attr => {
                    let val = row[attr.key];
                    if(!val || !attr.items.length) {
                        return;
                    }

                    attr.items.forEach(item => {
                        if(val & item.id) {
                            attr.values.push(item);
                        }
                    });
                });
                const dates = []
                this.dates.forEach(item => {
                    if(row.dates & item.bit_id) {
                        dates.push(item);
                    }
                });
                row.dates = dates;
            }
            this.editDialogVisible = true;
            this.editData = Object.assign({}, {name: '', code: '', parent_id: 0, dates: []}, row);
            // this.editData.parent_id = this.parents.length >= 1 ? this.parents[0].id : 0
        },
        submitEdit() {
            let params = null;
            let $submitPromise = null;
            if(this.top) {
                this.editData.parent_id = 0;
            }
            if(this.editData.id > 0) {
                $submitPromise = this.ListModel.update(this.editData).$promise;
            }
            else {
                params = Object.assign({}, this.editData);
                $submitPromise = this.ListModel.save(params).$promise;
            }

            $submitPromise
            .then(res => {
                this.editDialogVisible = false;
                this.loadItems();

                if(res.code && res.code !== 200) {
                    this.$message.error(res.message);
                    return;
                }
                this.editDialogVisible = false;
                this.$message({
                    message: '提交成功！',
                    type: 'success'
                });
            })
            .catch(err => {
                this.$message.error(err);
            });
        },
        loadAttrs() {
            const attrs = [
                // { type: 'role', key: 'roles', name: '场景' },
                { type: 'weekdays', key: 'weekdays', name: '使用限制' },
            ];

            return AttributeModel.get()
            .$promise
            .then(attrsMap => {
                return attrs.map(attr => {
                    attr.items = attrsMap[attr.type] || [];
                    attr.values = [];

                    return attr;
                });
            })
            .tap(attrs => {
                this.attrs = attrs;
            });
        },
        loadDates() {
            return DateModel.query({})
            .$promise
            .then(dates => {
                this.dates = dates.items;
            })
        },
        exportData() {
            window.location = '/ticket/export';
        },
        onAttrChange(attr) {
            this.editData[attr.key] = attr.values.reduce((val, item) => {
                return val | item.id;
            }, 0);
        },
    }
});
</script>
